// bubble is an array
// 0 -> radius
// 1 -> x
// 2 -> height
// 3 -> speed px / s
// 4 -> alpha * 100

(function(global){

var random = Math.random;
var parseInt = global.parseInt;

function BubblesUp(opt){
    this.bubbles = new Array(opt.num || 100);
    this.screen = opt.screen || {width: 800, height: 600};
    this.radius = opt.radius || {start: 2, end: 5};
    this.speed = opt.speed || {start: 5, end: 10};
    this.alpha = opt.alpha || {start: 30, end: 50};
}

BubblesUp.prototype._genBubble = function genBubble(fromTop)
{
    var bubble = [];
    var radius = this.radius;
    var speed = this.speed;
    var alpha = this.alpha;
    bubble[0] = parseInt(random() * (radius.end - radius.start)) + radius.start;
    bubble[1] = parseInt(random() * this.screen.width);
    bubble[2] = fromTop ? 0 : parseInt(random() * this.screen.height);
    bubble[3] = parseInt(random() * (speed.end - speed.start)) + speed.start;
    bubble[4] = parseInt(random() * (alpha.end - alpha.start)) + alpha.start;
    return bubble;
}

BubblesUp.prototype.gen = function(){
    var bubbles = this.bubbles;
    for(var i = 0; i < bubbles.length; i++)
        bubbles[i] = this._genBubble();
}

BubblesUp.prototype.paint = function(animator){
    var draw = function(e, i, c){
	var ctx = animator.ctx;
	var height = animator.height;
	ctx.save();
	ctx.beginPath();
	ctx.arc(e[1], e[2], e[0], 0, 2 * Math.PI, false);
	ctx.closePath();
	ctx.fillStyle = 'rgba(255, 255, 255, ' + e[4] / 100 + ')';
	ctx.fill();
	ctx.restore();
    };
    this.paint = function(animator){
	this.bubbles.forEach(draw);
    };
    this.paint(animator);
}

BubblesUp.prototype.update = function(animator){
    var ctx = animator.ctx;
    var self = this;
    function updateBubble(e, i, c){
	e[2] += e[3] * animator.delta / 1000;
	if(e[2] > self.screen.height)
	    self.bubbles[i] = self._genBubble(true);
    }
    
    this.update = function(animator){
	this.bubbles.forEach(updateBubble);
    }
    this.update(animator);
}

global.BubblesUp = BubblesUp;

})(this);

(function(global){
    
    var cvs = $('#bg-canvas').get(0);
    var box = cvs.getBoundingClientRect();
    var width = box.width;
    var height = box.height;
    cvs.setAttribute('width', width);
    cvs.setAttribute('height', height);

    if(typeof cvs.getContext === 'undefined')
	return; // canvas not supported

    var ctx = cvs.getContext('2d');
    var bbs = new BubblesUp({
	width: width,
	sStart: 30,
	sOffset: 20,
	num: 500
    });
    bbs.gen();
    var animator = new Animator(ctx, width, height, bbs);
    animator.animate();
})(this);
